/**
 * 
 */
package com.effectivsocial.extension.plugin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.josql.Query;
import org.josql.QueryResults;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @author Dhrubo
 * 
 */
@Named
@Slf4j
public class StartupPluginProcessor implements
		ApplicationListener<ContextRefreshedEvent> {

	private boolean processed = false;

	public void onApplicationEvent(ContextRefreshedEvent event) {

		if (!processed) {
			processed = true;
			log.info("##### Processing startup plugins.");

			Map<String, StartupPlugin> plugins = event.getApplicationContext()
					.getBeansOfType(StartupPlugin.class);
						
			List<StartupPlugin> list = new ArrayList<StartupPlugin>(plugins.values());
			
			String SQL = "SELECT * FROM com.effectivsocial.extension.plugin.StartupPlugin order by order";
			
			Query query = new Query();
			List<StartupPlugin> sortedPlugins = null;
			try {
				query.parse(SQL);
				QueryResults results = query.execute(list);
				sortedPlugins = results.getResults();
			} catch (Exception e) {
				log.error("Error", e);
				throw new RuntimeException(e);
			}
			
			log.info("##### Start up plugins = {}" ,  sortedPlugins);
			
			for(StartupPlugin plugin : sortedPlugins){
				plugin.preProcess(event.getApplicationContext());
				plugin.process(event.getApplicationContext());
				plugin.postProcess(event.getApplicationContext());
			}
		}
	}

}
